import request from '/src/util/http/http.js';

export function getUrlQueryParameter(name) {
    const params = new URLSearchParams(window.location.search);
    return params.get(name);
}

async function safeRequest(requestFn, url, operationName, data = undefined) {
    try {
        let result;
        if (data !== undefined) {
            result = await requestFn(url, data);
        } else {
            result = await requestFn(url);
        }
        return result;
    } catch (error) {
        const errorMsg = `${operationName}失败: ${error.message || '未知错误'}`;
        console.error(errorMsg, error);
        // 可以选择重新抛出，也可以包装成统一错误
        throw new Error(errorMsg);
    }
}

export function createApiService(baseUrl, operations) {
    const service = {};
    operations.forEach(({ method, path, name, type = 'get' }) => {
        service[method] = async (data) => {
            const requestFn = type.toLowerCase() === 'post'
                ? request.post
                : request.get;

            const config = type.toLowerCase() === 'post'
                ? data
                : { params: data }; // GET 请求参数放 params 里

            return await safeRequest(
                requestFn,
                `${baseUrl}${path}`,
                name,
                config
            );
        };
    });
    return service;
}